package com.slf.engine.threads;


import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.slf.engine.common.SysContants;
import com.slf.engine.common.SysContext;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.services.IEVCService;
import com.slf.engine.services.IReloadService;
import com.slf.engine.services.impl.EVCServiceImpl;
import com.slf.engine.services.impl.ReloadServiceImpl;
public class MainThread extends Thread {

	private static final Logger log = Logger.getLogger(MainThread.class);
	private static boolean isConnect = false;
	public MainThread()
	{
		log.log(Priority.INFO, "EVC充值主线程启动");
		init();
	}
	
	public void init()
	{
		IEVCService connService = new EVCServiceImpl();
		if(!connService.doLoginEVC())
		{			
			log.log(Priority.INFO, "EVC服务器登录失败");
			return;
		}
		new HeartThread().start();
		isConnect = true;
		IReloadService reloadService = new ReloadServiceImpl();
		reloadService.reloadUnSendOrder();
		reloadService.reloadUnQueryOrder();
		reloadService.reloadUnNoticeOrder();
		SysContext.IS_TREAD_RUN = true;
		for(int i = 0; i < SysContants.MAX_TASKNUM; i++)
		{
			SendThread sendThread = new SendThread(SysContext.THREAD_GROUP);
			sendThread.start();
		}
		
		
		new GetRequestThread().start();
		new NoticeThread().start();
	}
	
	public void run()
	{
		while(isConnect)
		{
			synchronized (SysContext.THREAD_GROUP) {
				log.log(Priority.INFO, "当前交易线程数【" + SysContext.THREAD_GROUP.activeCount() + "】");
				if(SysContext.THREAD_GROUP.activeCount() < SysContants.MAX_TASKNUM)
				{
					SendThread sendThread = new SendThread(SysContext.THREAD_GROUP);
					sendThread.start();
				}
			}
			try {
				Thread.sleep(300000); //5分钟监控一次线程状态
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
			}
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		log.log(Priority.INFO, "主线程被销毁");
		SysContext.IS_TREAD_RUN = false;
	}
}
